#-*- coding:UTF-8 -*-
'''
Created on 2013-6-7

@author: hanjiewu
'''
'''
start_new_thread(function,
args, kwargs=None) 产生一个新的线程，在新线程中用指定的参数和可选的
kwargs 来调用这个函数。
allocate_lock() 分配一个LockType 类型的锁对象
exit() 让线程退出

LockType 类型锁对象方法
acquire(wait=None) 尝试获取锁对象
locked() 如果获取了锁对象返回True，否则返回False
release() 释放锁
'''
from time import ctime, sleep
import thread
loops = [4,2]
def loop(nloop, nsec, lock):
    print 'start loop ', nloop, 'at: ', ctime()
    sleep(nsec)
    print 'loop ', nloop, 'done at: ', ctime()
    lock.release()
def main(): 
    print 'starting at: ', ctime()
    locks = []
    
    nloops = range(len(loops))
    
    for i in nloops:
        lock = thread.allocate_lock()
        lock.acquire()
        locks.append(lock)
    
    for i in nloops:
        thread.start_new_thread(loop, (i,loops[i], locks[i]))
    for i in nloops:
        while locks[i].locked():pass
        
    print 'all DONE at: ', ctime()
main()